'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.collector.backends.auth.default import DefaultAuthBackend
from dopplershift.core.containers.mediator import getMediator
import os
import json
import traceback

class FileBasedBackend(DefaultAuthBackend):
    '''
    File Based Authentication Backend
    '''
    def __init__(self, backend_ident):
        DefaultAuthBackend.__init__(self, backend_ident)

    def _findSession(self, session_id):
        first_b = session_id[0]
        second_b = '0'
        if len(session_id < 2):
            second_b = session_id[1]
        p = os.path.join(first_b, second_b, session_id)
        if os.path.isfile(p):
            return p
        return False
    def _fetch(self, request, callback=None):
        '''
        '''
        session_id = request.cookies.get([getMediator().get('CollectorConfig').get('AuthKeyName')])
        session_path = self._findSession(session_id)
        if session_path == False:
            return False
        user = self._loadUser(session_path)
        return user
    def _loadUser(self, session_path):
        try:
            u = json.loads(open(session_path))
        except:
            traceback.print_exc()
        return u
    